<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 左侧树 -->
      <el-col :lg="4" :xs="24">
        <div class="grave-title">
          墓穴园区
          <el-button link type="primary" @click="handleAddYq">新增</el-button>
        </div>
        <el-card shadow="hover">
          <el-input v-model="deptName" placeholder="请输入关键词" prefix-icon="Search" clearable />
          <el-tree ref="deptTreeRef" class="mt-2" node-key="id" :data="deptOptions"
            :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false"
            :filter-node-method="filterNode" highlight-current default-expand-all
            @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span>{{ node.label }}</span>
                <div v-if="data.id">
                  <el-button link type="danger" icon="Delete" @click="remove(node, data)"></el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
          :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="墓穴区域" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入墓穴区域" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="逝者名称" prop="deadPersonName">
                  <el-input v-model="queryParams.deadPersonName" placeholder="请输入逝者名称" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="墓穴状态" prop="status">
                  <el-radio-group v-model="queryParams.status">
                    <el-radio-button label="全部" value="" />
                    <el-radio-button label="待售" :value="1" />
                    <el-radio-button label="预留" :value="2" />
                    <el-radio-button label="已使用" :value="3" />
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                  v-hasPermi="['cemetery:grave:add']">新增</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                  v-hasPermi="['cemetery:grave:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                  v-hasPermi="['cemetery:grave:remove']">删除</el-button>
              </el-col> -->
              <el-col :span="1.5">
                <el-button v-hasPermi="['tool:gen:import']" type="info" plain icon="Upload"
                  @click="handleImport">导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                  v-hasPermi="['cemetery:grave:export']">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <div class="grave-list" v-for="(item,index) in graveList" :key="index">
            <div class="grave-left">
              <div class="grave-img">
                <img :src="item.imgUrl">
                <div class="tag">{{item.type==1?'私人墓':item.type==2?'名人墓':'烈士墓'}}</div>
              </div>
              <div class="grave-desc">
                <div class="name">{{item.name}}</div>
                <div class="address">地址定位：{{item.location}}</div>
                <div class="update">最近更新时间：{{item.updateTime}}</div>
                <div class="update">最近更新人员：{{item.updateByName}}</div>
              </div>
            </div>
            <div class="grave-right">
              <div class="tag-r">
                <el-tag type="primary" v-if="item.status==1">待售</el-tag>
                <el-tag type="primary" v-if="item.status==2&&item.type==1">
                  预留：{{item.reservePerson}} {{item.reserveTime}}
                </el-tag>
                <el-tag type="primary" v-if="item.status==3&&item.type==1">
                  已使用：{{item.deadPersonNames}} {{item.buyTime}}
                </el-tag>
                <el-tag type="primary" v-if="item.status!=1&&item.type!=1">
                  已使用：{{item.martyrsName}} {{item.expirationTime}}
                </el-tag>
              </div>
              <div class="price">预售价: {{item.price}}元</div>
              <div class="group-btns">
                <el-button type="primary" size="small" @click="changeStatus(item,'业务办理')"
                  v-if="item.status==1">业务办理</el-button>
                <el-button type="primary" size="small" @click="handleDetail(item)"
                  v-if="item.status==2||item.status==3">查看</el-button>
                <el-button type="success" size="small" @click="changeStatus(item,'预留修改')"
                  v-if="item.status==2&&item.type==1">预留修改</el-button>
                <el-button type="success" size="small" @click="changeStatus(item,'使用修改')"
                  v-if="item.status==3||item.type!=1">使用修改</el-button>
                <el-button type="warning" size="small" @click="cancelStatus(item,'预留')"
                  v-if="item.status==2&&item.type==1">预留取消</el-button>
                <el-button type="warning" size="small" @click="cancelStatus(item,'使用')"
                  v-if="item.status==3||item.type!=1">使用取消</el-button>
                <el-button type="info" size="small" @click="handleUpdate(item)">墓穴修改</el-button>
              </div>
            </div>
          </div>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改墓穴对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="graveFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="墓穴园区">
              <el-input v-model="parkName" placeholder="请输入墓穴园区" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="墓穴区域">
              <el-input v-model="areaName" placeholder="请输入墓穴区域" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="墓穴排数">
              <el-input v-model="rowName" placeholder="请输入墓穴排数" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="墓穴类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio label="私人墓" :value="1" />
                <el-radio label="名人墓" :value="2" />
                <el-radio label="烈士墓" :value="3" />
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="墓穴号数" prop="number">
              <el-input-number v-model="form.number" :min="1" :max="99999" placeholder="请输入墓穴号数" :step="1"
                :step-strictly="true" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="墓穴图片" prop="img">
              <imageUpload v-model="form.img" @getModelUrl="getImgUrl" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="墓穴位置" prop="location">
              <el-input v-model="form.location" placeholder="请选择墓穴位置"
                :disabled="!form.latitude||!form.longitude">
                <template #append>
                  <el-icon style="cursor: pointer;" @click="chooseMap">
                    <Location />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预售价" prop="price">
              <el-input-number v-model="form.price" :min="0.01" :max="1000000.00" :precision="2" placeholder="请输入预售价"
                style="width: 100%;">
                <template #suffix>
                  <span>RMB</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 业务办理对话框 -->
    <el-dialog :title="ywDialog.title" v-model="ywDialog.visible" width="800px" append-to-body>
      <el-form ref="graveFormRef" :model="form" :rules="rules" label-width="80px">
        <div v-if="type==1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="业务类型" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :value="2">预留</el-radio>
                  <el-radio :value="3">已使用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="安葬方式" prop="buriedType">
                <el-radio-group v-model="form.buriedType">
                  <el-radio :value="1">单人墓</el-radio>
                  <el-radio :value="2">双人墓</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.status==2">
            <el-col :span="12">
              <el-form-item label="预留人员" prop="reservePerson">
                <el-input v-model="form.reservePerson" placeholder="请输入预留人员" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="reservePhone">
                <el-input v-model="form.reservePhone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预留时间" prop="reserveTime">
                <el-date-picker clearable v-model="form.reserveTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择预留时间" :disabled-date="disabledDate" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预留原因" prop="reserveReason">
                <el-input v-model="form.reserveReason" placeholder="请输入预留原因" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.status==3">
            <el-col :span="12">
              <el-form-item label="逝者姓名" prop="deadPersonId" v-if="form.buriedType==2">
                <el-select v-model="form.deadPersonId" multiple :multiple-limit="2" clearable filterable
                  placeholder="请选择逝者" style="width: 100%">
                  <el-option v-for="item in deadPerson" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="逝者姓名" prop="deadPersonId" v-else>
                <el-select v-model="form.deadPersonId" clearable filterable placeholder="请选择逝者" style="width: 100%">
                  <el-option v-for="item in deadPerson" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="购买时间" prop="buyTime">
                <el-date-picker clearable v-model="form.buyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择购买时间" :disabled-date="disabledDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.buriedType==2">
              <el-form-item label="到期时间" prop="expirationTime">
                <el-date-picker clearable v-model="form.expirationTime" type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择到期时间" :disabled-date="disabledDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合葬时间" prop="buriedTime">
                <el-date-picker clearable v-model="form.buriedTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择合葬时间" :disabled-date="disabledDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际售价" prop="buyPrice">
                <el-input-number v-model="form.buyPrice" :min="0.01" :max="1000000.00" :precision="2"
                  placeholder="请输入实际售价" style="width: 100%;">
                  <template #suffix>
                    <span>RMB</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-else>
          <el-row>
            <el-col :span="12">
              <el-form-item label="名人烈士" prop="martyrsId">
                <el-select v-model="form.martyrsId" clearable filterable placeholder="请选择名人烈士" style="width: 100%">
                  <el-option v-for="item in deadMartyr" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期时间" prop="expirationTime">
                <el-date-picker clearable v-model="form.expirationTime" type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择到期时间" :disabled-date="disabledDate" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitBusinessForm">确 定</el-button>
          <el-button @click="ylcancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 园区新增对话框 -->
    <el-dialog :title="yqDialog.title" v-model="yqDialog.visible" width="780px" append-to-body>
      <el-form ref="yqFormRef" :model="yqform" :rules="yqrules" label-width="80px">
        <el-form-item label="">
          <el-radio-group v-model="parkType">
            <el-radio :value="1">批量新增</el-radio>
            <el-radio :value="2">单个新增</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="墓穴园区" prop="name">
          <el-input v-model="yqform.name" placeholder="请输入墓穴园区" />
        </el-form-item>
        <el-form-item label="墓穴区域" prop="areaStart" v-if="parkType==1">
          <el-input v-model="yqform.areaStart" placeholder="请输入墓穴区域" style="width: 200px; margin-right: 10px;" />
          -
          <el-input v-model="yqform.areaEnd" placeholder="请输入墓穴区域" style="width: 200px; margin-left: 10px;" />
        </el-form-item>
        <el-form-item label="墓穴排次" prop="rowStart" v-if="parkType==1">
          <el-input v-model="yqform.rowStart" placeholder="请输入墓穴排次" style="width: 200px; margin-right: 10px;" />
          -
          <el-input v-model="yqform.rowEnd" placeholder="请输入墓穴排次" style="width: 200px;margin-left: 10px;" />
        </el-form-item>
        <el-form-item label="墓穴区域" prop="area" v-if="parkType==2">
          <el-input v-model="yqform.area" placeholder="请输入墓穴区域" />
        </el-form-item>
        <el-form-item label="墓穴排次" prop="row" v-if="parkType==2">
          <el-input v-model="yqform.row" placeholder="请输入墓穴排次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="yqbuttonLoading" type="primary" @click="yqsubmitForm">确 定</el-button>
          <el-button @click="yqcancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 地图对话框 -->
    <el-dialog :title="mapDialog.title" v-model="mapDialog.visible"  v-if="mapDialog.visible"
      width="800px" append-to-body>
      <MapPicker @point-selected="handlePointSelected"
        :longitude="form.longitude"
        :latitude="form.latitude"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLocation">确 定</el-button>
          <el-button @click="mapDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Grave" lang="ts">
  import {

    listGrave, getGrave, delGrave, addGrave, updateGrave,businessGrave, listParkTreeList,
    addPark, addBatchPark, delPark, getPark

  } from '@/api/cemetery/grave';
  import { GraveVO, GraveQuery, GraveForm, ParkVO, ParkQuery, ParkForm } from '@/api/cemetery/grave/types';
  import { getTemplate } from '@/api/cemetery/deadPerson';
  import { listDeadPerson } from '@/api/cemetery/deadPerson';
  import { listMartyrs } from '@/api/cemetery/martyrs'

  import router from '@/router';

  import { globalHeaders } from '@/utils/request';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const graveList = ref<GraveVO[]>([]);
  const buttonLoading = ref(false);
  const yqbuttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const templateUrl = ref('')
  const currentLocation = ref(null);

  const deptName = ref('')
  const deptOptions = ref([])
  const type = ref('')
  const deadPerson = ref([]);
  const deadMartyr = ref([]);

  /*** 用户导入参数 */
  const upload = reactive<ImportOption>({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: globalHeaders(),
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/system/user/importData'
  });

  const queryFormRef = ref<ElFormInstance>();
  const graveFormRef = ref<ElFormInstance>();
  const yqFormRef = ref<ElFormInstance>();
  const uploadRef = ref<ElUploadInstance>();
  const deptTreeRef = ref<ElTreeInstance>();
  const currentSelectedNode = ref(null);
  const parentNodes = ref([]);
  const parkName = ref(null);
  const areaName = ref(null);
  const rowName = ref(null);


  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const mapDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const ywDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const yqDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  // 验证函数：仅允许中英文，长度2-20
  const validateName = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请输入内容'));
    }
    // 正则表达式：匹配中文字符和英文字母
    const reg = /^[\u4e00-\u9fa5a-zA-Z]+$/;

    if (!reg.test(value)) {
      callback(new Error('仅允许输入中文或英文'));
    } else if (value.length < 2 || value.length > 20) {
      callback(new Error('长度需在2到20个字符之间'));
    } else {
      callback();
    }
  };
  // 验证函数：仅允许中英文，长度2-200
  const validateReason = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请输入内容'));
    }
    // 正则表达式：匹配中文字符和英文字母
    const reg = /^[\u4e00-\u9fa5a-zA-Z]+$/;

    if (!reg.test(value)) {
      callback(new Error('仅允许输入中文或英文'));
    } else if (value.length < 2 || value.length > 200) {
      callback(new Error('长度需在2到20个字符之间'));
    } else {
      callback();
    }
  };
  // 验证函数：仅允许数字，长度6-20
  const validateNumber = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请输入数字'));
    }
    // 检查是否为纯数字
    if (!/^\d+$/.test(value)) {
      callback(new Error('只能输入数字'));
    }
    // 检查长度
    else if (value.length < 6) {
      callback(new Error('最少需要6位数字'));
    }
    else if (value.length > 20) {
      callback(new Error('最多不能超过20位数字'));
    }
    else {
      callback();
    }
  };
  const disabledDate = (time : Date) => {
    return time.getTime() < Date.now()
  }
  const initFormData : GraveForm = {
    id: undefined,
    name: undefined,
    parkId: undefined,
    areaId: undefined,
    rowId: undefined,
    type: undefined,
    number: undefined,
    img: undefined,
    imgUrl: undefined,
    longitude: undefined,
    latitude: undefined,
    location: undefined,
    price: undefined,
    status: undefined,
    reservePerson: undefined,
    reserveReason: undefined,
    reservePhone: undefined,
    reserveTime: undefined,
    deadPersonId: undefined,
    martyrsId: undefined,
    buyTime: undefined,
    expirationTime: undefined,
    buriedTime: undefined,
    buyPrice: undefined,
    orderNum: undefined,
    buriedType: undefined,
  }
  const data = reactive<PageData<GraveForm, GraveQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      name: undefined,
      parkId: undefined,
      areaId: undefined,
      rowId: undefined,
      type: undefined,
      number: undefined,
      img: undefined,
      imgUrl: undefined,
      longitude: undefined,
      latitude: undefined,
      location: undefined,
      price: undefined,
      status: '',
      reservePerson: undefined,
      reserveReason: undefined,
      reservePhone: undefined,
      reserveTime: undefined,
      deadPersonId: undefined,
      martyrsId: undefined,
      buyTime: undefined,
      expirationTime: undefined,
      buriedTime: undefined,
      buyPrice: undefined,
      orderNum: undefined,
      params: {
      }
    },
    rules: {
      name: [
        { required: true, message: "名称不能为空", trigger: "blur" }
      ],
      rowId: [
        { required: true, message: "排数不能为空", trigger: "blur" }
      ],
      type: [
        { required: true, message: "类型不能为空", trigger: "change" }
      ],
      number: [
        { required: true, message: "墓穴号数不能为空", trigger: "blur" }
      ],
      img: [
        { required: true, message: "墓穴图片不能为空", trigger: "blur" }
      ],
      longitude: [
        { required: true, message: "经度不能为空", trigger: "blur" }
      ],
      latitude: [
        { required: true, message: "纬度不能为空", trigger: "blur" }
      ],
      location: [
        { required: true, message: "位置不能为空", trigger: "blur" }
      ],
      price: [
        { required: true, message: "预售价不能为空", trigger: "blur" }
      ],
      status: [
        { required: true, message: "状态不能为空", trigger: "change" }
      ],
      reservePerson: [
        { required: true, message: "预留人员不能为空", trigger: "blur" },
        { validator: validateName, trigger: 'blur' }
      ],
      reserveReason: [
        { required: true, message: "预留原因不能为空", trigger: "blur" },
        { validator: validateReason, trigger: 'blur' }
      ],
      reservePhone: [
        { required: true, message: "联系方式不能为空", trigger: "blur" },
        { validator: validateNumber, trigger: 'blur' }
      ],
      reserveTime: [
        { required: true, message: "预留时间不能为空", trigger: "blur" }
      ],
      deadPersonId: [
        { required: true, message: "逝者不能为空", trigger: "blur" }
      ],
      martyrsId: [
        { required: true, message: "名人烈士不能为空", trigger: "blur" }
      ],
      buyTime: [
        { required: true, message: "购买时间不能为空", trigger: "blur" }
      ],
      expirationTime: [
        { required: true, message: "到期时间不能为空", trigger: "blur" }
      ],
      buriedTime: [
        { required: true, message: "合葬时间不能为空", trigger: "blur" }
      ],
      buyPrice: [
        { required: true, message: "实际售价不能为空", trigger: "blur" }
      ],
      orderNum: [
        { required: true, message: "显示顺序不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);


  const parkType = ref(1)
  const yqinitFormData : ParkForm = {
    id: undefined,
    name: undefined,
    area: undefined,
    row: undefined,
    areaStart: undefined,
    areaEnd: undefined,
    rowStart: undefined,
    rowEnd: undefined,
  }
  const yqdata = reactive<PageData<ParkForm, ParkQuery>>({
    yqform: { ...yqinitFormData },
    yqqueryParams: {
      pageNum: 1,
      pageSize: 10,
      name: undefined,
      area: undefined,
      row: undefined,
      areaStart: undefined,
      areaEnd: undefined,
      rowStart: undefined,
      rowEnd: undefined,
      params: {
      }
    },
    yqrules: {
      name: [
        { required: true, message: "墓穴园区名称不能为空", trigger: "blur" }
      ],
      area: [
        { required: true, message: "墓穴区域不能为空", trigger: "blur" }
      ],
      row: [
        { required: true, message: "墓穴排次不能为空", trigger: "blur" }
      ],
      areaStart: [
        { required: true, message: "墓穴区域不能为空", trigger: "blur" }
      ],
      areaEnd: [
        { required: true, message: "墓穴区域不能为空", trigger: "blur" }
      ],
      rowStart: [
        { required: true, message: "墓穴排次不能为空", trigger: "blur" }
      ],
      rowEnd: [
        { required: true, message: "墓穴排次不能为空", trigger: "blur" }
      ],
    }
  });

  const { yqqueryParams, yqform, yqrules } = toRefs(yqdata);

  /** 查询园区下拉树结构 */
  const getParkTree = async () => {
    const params = {}
    const res = await listParkTreeList(params);
    deptOptions.value = transformStructure(res.data);
    console.log(deptOptions.value)
  };
  const transformStructure = (originalData) => {
    return originalData.map(item => {
      // 处理园区级别
      const transformed = {
        name: item.name,
        children: item.area ? item.area.map(areaItem => {
          // 处理区域级别
          return {
            name: areaItem.name,
            children: areaItem.rows ? areaItem.rows.map(rowItem => {
              // 处理排次级别
              return {
                id: rowItem.id,
                name: rowItem.name
              };
            }) : []
          };
        }) : []
      };
      return transformed;
    });
  }

  const remove = async (node, data) => {
    // const parent = node.parent
    // const children = parent?.data.children || parent?.data
    // const index = children.findIndex((d) => d.id === data.id)
    // children.splice(index, 1)
    // deptOptions.value = [...deptOptions.value]
    await proxy?.$modal.confirm('是否确认删除？');
    await delPark(data.id);
    proxy?.$modal.msgSuccess("删除成功");
    await getParkTree();
  }
  /** 通过条件过滤节点  */
  const filterNode = (value : string, data : any) => {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
  };
  /** 根据名称筛选部门树 */
  watchEffect(
    () => {
      deptTreeRef.value?.filter(deptName.value);
    },
    {
      flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
    }
  );

  // 查找所有父节点的递归函数
  const findParentNodes = (node, tree, path = []) => {
    for (const item of tree) {
      if (item.id === node.id) {
        return path;
      }
      if (item.children) {
        const found = findParentNodes(node, item.children, [...path, item]);
        if (found) return found;
      }
    }
    return null;
  };

  const handleNodeClick = (node) => {
    currentSelectedNode.value = node;
    parentNodes.value = findParentNodes(node, deptOptions.value) || [];
    console.log(currentSelectedNode.value)
    console.log(parentNodes.value)
    parkName.value = parentNodes.value[0]?parentNodes.value[0].name:''
    areaName.value = parentNodes.value[1]?parentNodes.value[1].name:''
    rowName.value = currentSelectedNode.value.name?currentSelectedNode.value.name:''

  };



  /** 查询墓穴列表 */
  const getList = async () => {
    loading.value = true;
    console.log(queryParams.value)
    const res = await listGrave(queryParams.value);
    graveList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    graveFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : GraveVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    console.log(currentSelectedNode.value)
    if (currentSelectedNode.value && currentSelectedNode.value.id) {
      reset();
      form.value.parkId = currentSelectedNode.value.id
      form.value.type = 1
      dialog.visible = true;
      dialog.title = "添加墓穴";
    } else {
      proxy?.$modal.msgWarning("请选择墓穴排次");
    }
  }
  const getImgUrl = (val : any) => {
    console.log(val)
    form.value.imgUrl = val
  }
  const chooseMap = () => {
    mapDialog.visible = true;
    mapDialog.title = "选择位置";
  }
  const handlePointSelected = (location) => {
    currentLocation.value = location
    console.log('选择的位置:', location)
  }
  const submitLocation = () => {
    if( !currentLocation.value ){
      proxy?.$modal.msgWarning("请选择位置");
    }else{
      form.value.location = currentLocation.value.address
      form.value.longitude = currentLocation.value.lng
      form.value.latitude = currentLocation.value.lat
      mapDialog.visible = false
    }

  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: GraveVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGrave(_id);
    Object.assign(form.value, res.data);

    const ress = await getPark(res.data.parkId);
    parkName.value = ress.data ? ress.data.name : ''
    areaName.value =  ress.data ? ress.data.area : ''
    rowName.value = ress.data ?  ress.data.row : ''

    dialog.visible = true;
    dialog.title = "修改墓穴";
  }

  /** 提交按钮 */
  const submitForm = () => {
    graveFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if( form.value.buriedType == 2 ){
          form.value.deadPersonId = form.value.deadPersonId ? form.value.deadPersonId.toString() : ''
        }
        if (form.value.id) {
          await updateGrave(form.value).finally(() => buttonLoading.value = false);
        } else {
          form.value.name = parkName.value + areaName.value + rowName.value + form.value.number + '号'
          await addGrave(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        ywDialog.visible = false;
        await getList();
      }
    });
  }
  const submitBusinessForm = () => {
    graveFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if( form.value.buriedType == 2 ){
          form.value.deadPersonId = form.value.deadPersonId ? form.value.deadPersonId.toString() : ''
        }
        if (form.value.id) {
          await businessGrave(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        ywDialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: GraveVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除墓穴编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delGrave(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导入按钮操作 */
  const handleImport = () => {
    upload.title = '逝者导入';
    upload.open = true;

  };
  /**获取模板地址**/
  const getTemplateUrl = async () => {
    const params = {
      pageNum: 1,
      pageSize: 10,
      dictTyp: 'template',
      dictLabel: 'deadPerson',
    }
    const res = await getTemplate(params);
    templateUrl.value = res.rows[0].dictValue
  }
  /** 下载模板操作 */
  const importTemplate = () => {
    //proxy?.download('system/dict/data/list?pageNum=1&pageSize=10&dictType=template&dictLabel=deadPerson', {}, `user_template_${new Date().getTime()}.xlsx`);
    window.open(templateUrl.value)
  };

  /** 提交上传文件 */
  function submitFileForm() {
    uploadRef.value?.submit();
  }
  /**文件上传中处理 */
  const handleFileUploadProgress = () => {
    upload.isUploading = true;
  };
  /** 文件上传成功处理 */
  const handleFileSuccess = (response : any, file : UploadFile) => {
    upload.open = false;
    upload.isUploading = false;
    uploadRef.value?.handleRemove(file);
    ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
      dangerouslyUseHTMLString: true
    });
    getList();
  };

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('cemetery/grave/export', {
      ...queryParams.value
    }, `grave_${new Date().getTime()}.xlsx`)
  }

  const changeStatus = async (row, title) => {
    reset();
    type.value = row.type
    const _id = row?.id || ids.value[0]
    const res = await getGrave(_id);
    Object.assign(form.value, res.data);
    if( form.value.buriedType == 2 ){
      form.value.deadPersonId =  form.value.deadPersonId.split(',')
    }
    if( row.status == 1 && row.type == 1 ){
      form.value.status = 2
    }else if( row.status == 1) {
      form.value.status = 3
    }
    ywDialog.title = title;
    ywDialog.visible = true;
  }
  const ylcancel = () => {
    ywDialog.visible = false;
  }
  const cancelStatus = async (row, title) => {
    await proxy?.$modal.confirm('确定取消该' + title + '？');
    reset();
    const res = await getGrave(row.id);
    Object.assign(form.value, res.data);
    form.value.status = 1
    form.value.reservePerson = ''
    form.value.reserveReason = ''
    form.value.reservePhone = ''
    form.value.reserveTime = null
    form.value.deadPersonId = ''
    form.value.martyrsId = ''
    form.value.buyTime = null
    form.value.expirationTime = null
    form.value.buriedTime = null
    form.value.buyPrice = ''
    await updateGrave(form.value);
    proxy?.$modal.msgSuccess("取消成功");
    getList();
  }

  const handleDetail = (row) => {
    router.push('/ledger/graveDetail?id='+row.id);
  }

  const handleAddYq = () => {
    parkType.value = 1
    yqform.value = { ...yqinitFormData };
    yqDialog.title = '园区新增';
    yqDialog.visible = true;
  }
  const yqcancel = () => {
    yqDialog.visible = false;
  }
  /** 园区新增提交按钮 */
  const yqsubmitForm = () => {
    yqFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        yqbuttonLoading.value = true;
        if (parkType.value == 1) {
          await addBatchPark(yqform.value).finally(() => yqbuttonLoading.value = false);
        } else {
          await addPark(yqform.value).finally(() => yqbuttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        yqDialog.visible = false;
        await getParkTree();
      }
    });
  }

  /** 查询逝者信息列表 */
  const getDeadPersonList = async () => {
    const params = {
      pageNum: 1,
      pageSize: 1000,
    }
    const res = await listDeadPerson(params);
    deadPerson.value = res.rows;
  }

  /** 查询名人烈士列表 */
  const getMartyrsList = async () => {
    const params = {
      pageNum: 1,
      pageSize: 1000,
    }
    const res = await listMartyrs(params);
    deadMartyr.value = res.rows;
  }

  onMounted(() => {
    getParkTree();
    getDeadPersonList()
    getMartyrsList()
    getList();
  });
</script>
<style lang="scss">
  .grave-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    background: #f5f5f5;
    padding: 10px;
  }

  .grave-list {
    display: flex;
    font-size: 14px;
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #f5f5f5;

    .grave-left {
      display: flex;
      width: 60%;

      .grave-img {
        width: 180px;
        height: 110px;
        position: relative;
        margin-right: 10px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .tag {
          position: absolute;
          left: 0;
          top: 0;
          z-index: 10;
          width: 80px;
          height: 26px;
          background: #f5f5f5;
          text-align: center;
          line-height: 26px;
        }
      }

      .grave-desc {
        height: 110px;
        padding: 5px 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
    }

    .grave-right {
      padding: 10px 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: space-between;

      .price {
        color: #f00;
        margin: 10px 0;
      }
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
